<template>
  <div class="food-list" v-if="index === 0">
    <van-tree-select
        v-model:main-active-index="activeIndex"
        height="88vw"
        :items="items"
        @click-nav="navClick"
    >
      <template #content>
        <div v-for="(item,index) in subItem" class="item-bg">
          <ListItem :item = "item"
            :handleAdd = "handleAdd"
            :handleChange = "handleChange"
          ></ListItem>
        </div>
      </template>
    </van-tree-select>
  </div>

  <div v-else>
    {{ foodData.content }}
  </div>
</template>

<script>
import {reactive, toRefs} from "vue";
import ListItem from "@/components/ListItem/index.vue";
  export default {
    components: {
      ListItem
    },
    props: ['index','foodData'],
    setup(props){
      let data = reactive({
        activeIndex: 0,
        // items: [{ text: '全部商品1'},{ text: '全部商品2'}]
        item: [],
        subItem:[]
      });
      // 初始化数据
      const initData = () => {
        let newArray = []
        props.foodData?.items?.forEach((item,index)=>{
          newArray.push({
            text: item.text,
          })
          // 重复选择当前项
          if(data.activeIndex === index){
            data.subItem = item.children
          }
        })
        // 释放
        data.items = newArray
      }
      initData();

      const navClick= (i) => {
        // 打印点击索引值
        console.log(i)
        data.activeIndex = i;
        initData();
      }

      const handleAdd = (id) => {
        data.subItem.forEach((item, index) => {
          if(item.id == id){
            item.add = false
            item.num += 1
          }
        })
      }
      // 对照vant文档  点击步进器时  除了改变value值 还要改变subItem的值
      const handleChange = (value,detail) => {
        data.subItem.forEach((item) => {
          if(item.id === detail.name){
            item.name = value;
          }
        })

        // console.log("subItem",data.subItem)
      }
      return {...toRefs(data),navClick,handleAdd,handleChange}
    }
  }
</script>

<style lang="less" scoped>
.food-list {
  margin-top: 20px;
  .item-bg {
    padding: 10px;
  }
}
/deep/ .van-tree-select__item--active {
  color: #ffc400;
}
/deep/ .van-sidebar-item--select::before {
  background-color: #ffc400;
}
</style>